package com.meteor.downloader.videodownloader.utils

import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import com.facebook.FacebookSdk
import com.facebook.appevents.AppEventsLogger
import com.google.firebase.remoteconfig.ConfigUpdate
import com.google.firebase.remoteconfig.ConfigUpdateListener
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.FirebaseRemoteConfigException
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings
import com.meteor.downloader.videodownloader.BuildConfig
import com.meteor.downloader.videodownloader.admdm.AdInfoUtils.MDM_SHOW_AD_LIST
import com.meteor.downloader.videodownloader.clueft.ReceiverActionValue
import com.meteor.downloader.videodownloader.mdmBaseResult64
import com.meteor.downloader.videodownloader.mdmdata.DataLinkDefaultMdm
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_ALL_TWO_KEY
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_AY_PERIOD_VALUE
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_FB_INIT_CONFIG
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_LANGUAGE_START_CAN
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_LET_VALUE
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_LET_VALUE_DEFAULT
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_NOTIFY_CONFIG_VALUE
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_VIDEO_VALUE_LIST
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.YUN_MDM_FIRST_INIT
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.YUN_MDM_ID
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.mMdmVideoValueList
import com.reyun.solar.engine.OnAttributionListener
import com.reyun.solar.engine.SolarEngineConfig
import com.reyun.solar.engine.SolarEngineManager
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import org.json.JSONObject

object ApplicationMdmUtils {
    fun getConfigMdmData(context: Application) {
        val instanceJT = FirebaseRemoteConfig.getInstance()
        instanceJT.setConfigSettingsAsync(
            FirebaseRemoteConfigSettings.Builder().setMinimumFetchIntervalInSeconds(3600).build()
        )
        instanceJT.fetchAndActivate().addOnCompleteListener {
            if (it.isSuccessful) {
                //facebook的id;Token
                val snap1 = instanceJT.getString(MDM_FB_INIT_CONFIG)
                if (snap1.isNotEmpty()) {
                    initMdmFacebookValue(context, snap1)
                }
                //审核期间 strValue
                val snap2 = instanceJT.getString(MDM_AY_PERIOD_VALUE)
                if (snap2.isNotEmpty()) {
                    DataManagerMdmUtils.setDataKeyMdm(MDM_AY_PERIOD_VALUE, snap2)
                }
                //ad
                val snap3 = instanceJT.getString(MDM_SHOW_AD_LIST)
                if (snap3.isNotEmpty()) {
                    DataManagerMdmUtils.setDataKeyMdm(MDM_SHOW_AD_LIST, snap3)
                }
                //通知
                val snap4 = instanceJT.getString(MDM_NOTIFY_CONFIG_VALUE)
                if (snap4.isNotEmpty()) {
                    DataManagerMdmUtils.setDataKeyMdm(MDM_NOTIFY_CONFIG_VALUE, snap4)
                }
                //插页配置
                val snap5 = instanceJT.getString(MDM_LET_VALUE)
                if (snap5.isNotEmpty()) {
                    DataManagerMdmUtils.setDataKeyMdm(MDM_LET_VALUE, snap5)
                }
                //远程视频链接
                val snap6 = instanceJT.getString(MDM_VIDEO_VALUE_LIST)
                if (snap6.isNotEmpty()) {
                    DataManagerMdmUtils.setDataKeyMdm(MDM_VIDEO_VALUE_LIST, snap6)
                }
                //启动页控制参数 启动页是否跳转语言页 language home
                val snap7 = instanceJT.getString(MDM_LANGUAGE_START_CAN)
                if (snap7.isNotEmpty()) {
                    DataManagerMdmUtils.setDataKeyMdm(MDM_LANGUAGE_START_CAN, snap7)
                }
                //zm 尾缀 _fast_saver_12。
                val snap8 = instanceJT.getString(MDM_ALL_TWO_KEY)
                if (snap8.isNotEmpty()) {
                    DataManagerMdmUtils.setDataKeyMdm(MDM_ALL_TWO_KEY, snap8)
                }
            }
        }
        instanceJT.addOnConfigUpdateListener(object : ConfigUpdateListener {
            override fun onUpdate(config: ConfigUpdate) {
                if (config.updatedKeys.contains(MDM_FB_INIT_CONFIG) || config.updatedKeys.contains(
                        MDM_AY_PERIOD_VALUE
                    ) || config.updatedKeys.contains(
                        MDM_SHOW_AD_LIST
                    ) || config.updatedKeys.contains(MDM_NOTIFY_CONFIG_VALUE) || config.updatedKeys.contains(
                        MDM_LET_VALUE
                    ) || config.updatedKeys.contains(MDM_VIDEO_VALUE_LIST)
                    || config.updatedKeys.contains(MDM_LANGUAGE_START_CAN)
                    || config.updatedKeys.contains(MDM_ALL_TWO_KEY)
                ) {
                    instanceJT.activate().addOnCompleteListener {
                        if (it.isSuccessful) {
                            val snap1 = instanceJT.getString(MDM_FB_INIT_CONFIG)
                            if (snap1.isNotEmpty()) {
                                initMdmFacebookValue(context, snap1)
                            }

                            val snap2 = instanceJT.getString(MDM_AY_PERIOD_VALUE)
                            if (snap2.isNotEmpty()) {
                                DataManagerMdmUtils.setDataKeyMdm(MDM_AY_PERIOD_VALUE, snap2)
                            }
                            //ad
                            val snap3 = instanceJT.getString(MDM_SHOW_AD_LIST)
                            if (snap3.isNotEmpty()) {
                                DataManagerMdmUtils.setDataKeyMdm(MDM_SHOW_AD_LIST, snap3)
                            }
                            //通知
                            val snap4 = instanceJT.getString(MDM_NOTIFY_CONFIG_VALUE)
                            if (snap4.isNotEmpty()) {
                                DataManagerMdmUtils.setDataKeyMdm(MDM_NOTIFY_CONFIG_VALUE, snap4)
                            }
                            //插页配置
                            val snap5 = instanceJT.getString(MDM_LET_VALUE)
                            if (snap5.isNotEmpty()) {
                                DataManagerMdmUtils.setDataKeyMdm(MDM_LET_VALUE, snap5)
                            }
                            //远程视频链接
                            val snap6 = instanceJT.getString(MDM_VIDEO_VALUE_LIST)
                            if (snap6.isNotEmpty()) {
                                DataManagerMdmUtils.setDataKeyMdm(MDM_VIDEO_VALUE_LIST, snap6)
                            }

                            //启动页控制参数 启动页是否跳转语言页 language home
                            val snap7 = instanceJT.getString(MDM_LANGUAGE_START_CAN)
                            if (snap7.isNotEmpty()) {
                                DataManagerMdmUtils.setDataKeyMdm(MDM_LANGUAGE_START_CAN, snap7)
                            }
                            //zm 尾缀 _fast_saver_12。
                            val snap8 = instanceJT.getString(MDM_ALL_TWO_KEY)
                            if (snap8.isNotEmpty()) {
                                DataManagerMdmUtils.setDataKeyMdm(MDM_ALL_TWO_KEY, snap8)
                            }
                        }
                    }
                }
            }

            override fun onError(error: FirebaseRemoteConfigException) {

            }

        })
    }

    private fun initMdmFacebookValue(context: Application, config: String) {
        try {
            val result = config.mdmBaseResult64().split(";")
            FacebookSdk.setApplicationId(result[0])
            FacebookSdk.setClientToken(result[1])
            FacebookSdk.sdkInitialize(context)
            AppEventsLogger.activateApp(context)
            initMdmYun(context, result[0])
        } catch (_: Exception) {

        }
    }

    fun initMdmYun(context: Application, re: String) {
        if (!DataManagerMdmUtils.getDataKeyMdm(YUN_MDM_FIRST_INIT, false)) {
            DataManagerMdmUtils.setDataKeyMdm(YUN_MDM_FIRST_INIT, true)
            SolarEngineManager.getInstance().preInit(context, YUN_MDM_ID)
        }
        val seEConfig = SolarEngineConfig.Builder().setFbAppID(re).build()
        seEConfig.setOnAttributionListener(object : OnAttributionListener {
            override fun onAttributionSuccess(attribution: JSONObject) {
            }

            override fun onAttributionFail(errorCode: Int) {
            }
        })
        SolarEngineManager.getInstance().initialize(
            context, YUN_MDM_ID, seEConfig
        ) {}
    }

    fun initReceiverAction(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            context.registerReceiver(ReceiverActionValue(), IntentFilter().apply {
                addAction(Intent.ACTION_TIME_TICK)
                addAction(Intent.ACTION_PACKAGE_REMOVED)
                addAction(Intent.ACTION_PACKAGES_SUSPENDED)
                addAction(Intent.ACTION_PACKAGE_ADDED)
                addAction(Intent.ACTION_POWER_DISCONNECTED)
                addAction(Intent.ACTION_POWER_CONNECTED)
                addAction(Intent.ACTION_SCREEN_ON)
                addAction(Intent.ACTION_USER_PRESENT)
                addAction(Intent.ACTION_BATTERY_CHANGED)
                addAction(Intent.ACTION_CONFIGURATION_CHANGED)
            }, Context.RECEIVER_EXPORTED)
        } else {
            context.registerReceiver(ReceiverActionValue(), IntentFilter().apply {
                addAction(Intent.ACTION_TIME_TICK)
                addAction(Intent.ACTION_PACKAGE_REMOVED)
                addAction(Intent.ACTION_PACKAGES_SUSPENDED)
                addAction(Intent.ACTION_PACKAGE_ADDED)
                addAction(Intent.ACTION_POWER_DISCONNECTED)
                addAction(Intent.ACTION_POWER_CONNECTED)
                addAction(Intent.ACTION_SCREEN_ON)
                addAction(Intent.ACTION_USER_PRESENT)
                addAction(Intent.ACTION_BATTERY_CHANGED)
                addAction(Intent.ACTION_CONFIGURATION_CHANGED)
            })
        }
    }

    var mShowPageBack = false
    var mShowPageEnter = false
    fun getORIIntConfigValue() {
        try {
            if (!MdmTotalUtils.getMdmAppStatus()) {
                return
            }
            val values = DataManagerMdmUtils.getDataKeyMdm(MDM_LET_VALUE, MDM_LET_VALUE_DEFAULT)
                .mdmBaseResult64().split(";")
            mShowPageBack = values[0].split(":")[1] == "open"
            mShowPageEnter = values[1].split(":")[1] == "open"
            if (BuildConfig.DEBUG) {
//                mShowPageBack = true
//                mShowPageEnter = true
            }
        } catch (e: Exception) {
            mShowPageBack = false
            mShowPageEnter = false
        }
    }

    val mVideoMdmList = mutableListOf<DataLinkDefaultMdm>()
    var mEpVideo = ""
    fun getMeteorVideoSome() {
        if (mVideoMdmList.isNotEmpty()) return
        if (!MdmTotalUtils.getMdmAppStatus()) return
        try {
            val value =
                DataManagerMdmUtils.getDataKeyMdm(MDM_VIDEO_VALUE_LIST, mMdmVideoValueList)
                    .mdmBaseResult64()
            val moshi = Moshi.Builder().build()
            val typeData = Types.newParameterizedType(
                MutableList::class.java, DataLinkDefaultMdm::class.java
            )
            moshi.adapter<MutableList<DataLinkDefaultMdm>>(typeData).fromJson(value)?.let {
                mVideoMdmList.clear()
                mVideoMdmList.addAll(it)
                if (mVideoMdmList.isNotEmpty()) {
                    mEpVideo = mVideoMdmList[78].urlMdm ?: ""
                }
            }

        } catch (_: Exception) {
        }
    }
}